import React, { useState, useEffect } from 'react';
//模板对话框 2022-5-26
import DialogGeneralCategoriesData2 from "./DialogGeneralCategoriesData2"

//isOpen
//onOk
//onCancel
//loginedUser
function DialogTemplate(props) {

    const [catCount, setCatCount] = useState(0);
    const [catArray, setCatArray] = useState([]) ;


    const httpLoadTemplateList = function () {
        if( typeof props.loginedUser==='undefined' || props.loginedUser===null ) return ;
        const url1 = global.g_serverAPIRoot + 'omc/temlist?uid=' + props.loginedUser.uid;
        fetch(url1)  //GET
            .then(response => response.json())
            .then(result => {
                setCatArray(result.data) ;
                setCatCount( result.data.length ) ;
            }).catch(err => {
                console.log(err);// 505 404 ... errors
            });
    }


    useEffect(() => {
        httpLoadTemplateList() ;
    }, [props.loginedUser])


    const getCatName = function (catindex) {
        if( catindex >= 0 ){
            return catArray[catindex].catname ;
        }
        return "";

    }

    //列表头渲染
    const renderCatContentHeader = function (catindex) {
        return "" ;
    }

    //获取分类数据数组
    const getCatData = function (catindex) {
        if( catindex>=0 ){
            return catArray[catindex].data ;
        }
        return [];
    }


    //渲染单元格
    const renderDataCell = function (catindex, dataindex) {
        if( catArray.length === 0 ) return "";
        const dataArr = catArray[catindex].data ;
        if( dataArr===null || dataArr.length===0 ) return "" ;
        const data1 = dataArr[dataindex] ;
        return (
            <table>
                <tr>
                    <td>
                        <img style={{width:"150px",height:"150px",
                        objectFit:"contain",
                        border:"1px solid gray"}}
                            src={global.g_staticResourceRoot + data1.file+".thumb.png"}
                        />
                    </td>
                    <td  style={{textAlign:'left',paddingLeft:'10px'}}>
                        <h4>{data1.name}</h4>
                        <p>更新时间:{data1.ctime}</p>
                    </td>
                </tr>
            </table>
        );
    }

    const onOk = function (ci,di ) {
        if( catArray.length > 0 && catArray.length > ci )
        {
            if( catArray[ci].data.length > di ){
                let obj = catArray[ci].data[di] ;
                props.onOk(obj) ;
            }
        }
    }

    const onCancel = function () {
        props.onCancel();
    }

    return <DialogGeneralCategoriesData2
        isOpen={props.isOpen}
        dialogTitle={"选择绘图模板"}
        catCount={catCount}
        getCatName={getCatName}
        renderCatContentHeader={renderCatContentHeader}
        getCatData={getCatData}
        renderDataCell={renderDataCell}
        onOk={onOk}
        onCancel={onCancel}
    />;
}

export default DialogTemplate